package chapter_1;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Scanner;

/**
 * 测试java的InteAdress类
 * @author fulv
 */
public class InetAddressExample {
    public static void main(String[] args) {
        try{
            /**
             * 先获取本机的网络接口（网卡接口）
             * 然后获取对每个网络接口对应的IP地址（可能是ipv4,也可能是ipv6)
             */
            //获取网络接口列表
            Enumeration<NetworkInterface> networkInterfaceList = NetworkInterface.getNetworkInterfaces();

            //遍历每个接口
            while(networkInterfaceList.hasMoreElements()){
                NetworkInterface networkInterface = networkInterfaceList.nextElement();

                System.out.println("networkInterface name: "+networkInterface.getDisplayName());

                //获取address列表
                Enumeration<InetAddress> addressList = networkInterface.getInetAddresses();

                while(addressList.hasMoreElements()){
                    InetAddress address = addressList.nextElement();

                    System.out.println("hostname: "+address.getHostName() +"ip address: "+address.getHostAddress());
                }

            }
        }catch(SocketException e){
            e.printStackTrace();
        }

    }
}
